import { notification } from 'antd';
import { request } from 'umi';
import { isLocalHost, apiPath } from '@/app/config';

export function errorHandler(error: any) {
    const { response } = error;
    if (!response) {
        notification.error({
            description: '您的网络发生异常，无法连接服务器',
            message: '网络异常',
        });
    }
    return false;
}

export function requestInterceptor(url: any, { data, ...options }: any) {
    localStorage.setItem('lastUrl', url);
    localStorage.setItem('lastParams', JSON.stringify(data));
    const headers = {
        'Content-Type': 'application/json',
        Accept: 'application/json',
        token: localStorage.getItem('token'),
    };
    return {
        url: `${!isLocalHost ? apiPath : ''}${url}`,
        options: { ...options, data, method: 'POST', headers },
    };
}

export async function responseInterceptor(response: any) {
    const { code, msg, ...rest } = await response.clone().json();
    if (code === 200) {
        return { ...rest };
    }
    if (code === 201) {
        localStorage.setItem('token', msg);
        const url = localStorage.getItem('lastUrl') || '';
        const params = JSON.parse(localStorage.getItem('lastParams') || '');
        return request(url, { data: params });
    }
    if (code === 401) {
        return false;
    }
    notification.error({
        description: msg || '您的网络发生异常，无法连接服务器',
        message: '业务异常',
    });
    return false;
}
